<template>
  <!-- 人员管理 -->
  <div class="">
    <el-card style="margin-bottom: 10px">
      <FormComp
        :formConfig="searchFormConfig"
        @handleSure="handleQuery"
        @handleCancel="handleReset"
      />
    </el-card>
    <TabPaginComp
      :tableHead="tableHead"
      :tableData="tableData"
      :total="totalRef"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @handleOption="handleOption"
      :handleFun="handleFun"
    />
    <el-dialog
      v-model="flagOpen"
      :title="editId ? '编辑人员' : '新增人员'"
      width="40%"
      align-center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
    >
      <FormComp
        ref="formCompRef"
        :formConfig="formConfig"
        @handleSure="handleSure"
        @handleCancel="handleCancel"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { nextTick, onMounted, reactive, ref } from "vue";
import FormComp from "@/components/FormComp.vue";
import TabPaginComp from "@/components/TabPaginComp.vue";
import {
  addUserApi,
  delUserApi,
  editUserApi,
  exportUserApi,
  getUserApi,
} from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { exportUserInt, userFormInt } from "@/api/user/type";
import { useRouter } from "vue-router";
import { downloadBinaryFile } from "@/utils/download";
import { getGroupApi } from "@/api/group";

const router = useRouter();

const formCompRef = ref(null);

const tableData = ref([]);
const totalRef = ref(0);
const flagOpen = ref(false);
// 编辑id
let editId = ref(0);
// 表格上方操作按钮
let handleFun = ref([
  {
    label: "新增",
    type: "primary",
    prop: "add",
  },
  {
    label: "导出",
    type: "text",
    prop: "export",
  },
]);
/**
 * 人员表单
 */
const formConfig = reactive({
  items: [
    {
      label: "用户名",
      prop: "username",
      type: "Text",
      placeholder: "请输入用户名",
    },
    {
      label: "姓名",
      prop: "name",
      type: "Text",
      placeholder: "请输入姓名",
    },
    {
      label: "性别",
      prop: "gender",
      type: "Radio",
      placeholder: "请选择性别",
      optionList: [
        {
          label: "男",
          value: 1,
        },
        {
          label: "女",
          value: 0,
        },
      ],
    },
    {
      label: "职务",
      prop: "job",
      type: "Select",
      placeholder: "请选择职务",
      optionList: [
        {
          label: "主任",
          value: 1,
        },
        {
          label: "员工",
          value: 2,
        },
        {
          label: "后勤",
          value: 3,
        },
      ],
    },
    {
      label: "入职时间",
      prop: "entrydate",
      type: "DateAround",
      placeholder: "请选择入职时间",
    },
    {
      label: "所属部门",
      prop: "deptId",
      type: "Select",
      placeholder: "请选择所属部门",
      optionList: [],
    },
  ],
  rules: {
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
    job: [{ required: true, message: "请选择职务", trigger: "change" }],
    entrydate: [
      { required: true, message: "请选择入职时间", trigger: "change" },
    ],
    deptId: [{ required: true, message: "请选择所属部门", trigger: "change" }],
  },
  btnList: [
    {
      label: "确定",
      type: "primary",
      prop: "sure",
    },
    {
      label: "取消",
      prop: "cancel",
    },
  ],
});
/**
 * 管理员搜索表单
 */
const searchFormConfig = reactive({
  items: [
    {
      label: "姓名",
      prop: "name",
      type: "Text",
      placeholder: "请输入姓名",
      xl: 8,
      lg: 8,
      md: 12,
      sm: 24,
      xs: 24,
    },
    {
      label: "性别",
      prop: "gender",
      type: "Select",
      placeholder: "请选择性别",
      optionList: [
        {
          label: "男",
          value: 1,
        },
        {
          label: "女",
          value: 2,
        },
      ],
      xl: 8,
      lg: 8,
      md: 12,
      sm: 24,
      xs: 24,
    },
    {
      label: "入职时间",
      prop: "date",
      type: "Date",
      xl: 8,
      lg: 8,
      md: 12,
      sm: 24,
      xs: 24,
    },
  ],
  btnList: [
    {
      label: "查询",
      type: "primary",
      prop: "sure",
    },
    {
      label: "重置",
      prop: "cancel",
    },
  ],
});
// 表头
let tableHead = ref<any>([
  {
    label: "用户名",
    prop: "username",
  },
  {
    label: "姓名",
    prop: "name",
  },
  {
    label: "性别",
    prop: "gender",
  },
  {
    label: "职位",
    prop: "job",
  },
  {
    label: "所属部门",
    prop: "groupName",
  },
  {
    label: "入职时间",
    prop: "entrydate",
  },
  {
    label: "更新时间",
    prop: "updateTime",
  },
  {
    label: "操作",
    options: [
      {
        label: "编辑",
        prop: "edit",
        type: "primary",
      },
      {
        label: "删除",
        prop: "delete",
        type: "danger",
      },
    ],
  },
]);
// 搜索项
const searchForm = reactive<exportUserInt>({
  name: "",
  gender: 0,
  startTime: "",
  endTime: "",
});

/**
 * 获取部门数据
 */
const getGroup = () => {
  nextTick(() => {
    getGroupApi({ id: "", name: "" }).then((res) => {
      let groupList = res.data.list.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
      // console.log(2121, groupList);
      formConfig.items[formConfig.items.length - 1].optionList = groupList;
      // console.log(2121, formConfig.items[formConfig.items.length - 1].optionList);
    });
  });
};

// 页码信息
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
});

/**
 * 操作按钮
 */
const handleOption = (val: { prop: string; data: any }) => {
  switch (val.prop) {
    case "add":
      addUser();
      break;
    case "delete":
      // console.log("删除", val);
      delUser(val!.data!.id);
      break;
    case "edit":
      // console.log("编辑");
      editUser(val.data);
      break;
    case "export":
      getUser("export");
      break;

    default:
      break;
  }
};

/**
 * 查询
 */
const handleQuery = (val: exportUserInt) => {
  for (let key in val) {
    if (!val[key]) {
      val[key] = "";
    }
  }
  // console.log(2121, val);
  const { name, gender, date } = val;
  const params = {
    name,
    gender: gender,
    startTime: (date && date[0]) || "",
    endTime: (date && date[1]) || "",
  };
  Object.assign(searchForm, params);
  getUser();
};
/**
 * 重置
 */
const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    gender: "",
    startTime: "",
    endTime: "",
  });
  getUser();
};

/**
 * 确定
 */
const handleSure = (val: userFormInt) => {
  if (editId.value) {
    const params = {
      ...val,
      id: editId.value,
    };
    editUserApi(params).then((res) => {
      // console.log("res", res);
      if (res.code == 0) {
        ElMessage.success("编辑成功");
        handleCancel();
        getUser();
      } else if (res.code == -1) {
        ElMessage.info(res.msg);
      }
    });
    return;
  }
  addUserApi(val).then((res) => {
    // console.log('res', res);
    if (res.code == 0) {
      ElMessage.success("新增成功");
      handleCancel();
      getUser();
    } else if (res.msg.includes("登录")) {
      router.replace("/");
    }
  });
};
/**
 * 弹窗取消
 */
const handleCancel = () => {
  flagOpen.value = false;
  editId.value = 0;
};

/**
 * 新增
 */
const addUser = () => {
  flagOpen.value = true;
  getGroup();
};

/**
 * 编辑
 */
const editUser = async (data: {
  id: number;
  username: string;
  name: string;
  gender: number;
  job: number;
  entrydate: Date;
  deptId: number;
}) => {
  await getGroup();
  flagOpen.value = true;
  editId.value = data.id;
  nextTick(() => {
    console.log(21212, data);

    const { username, name, gender, job, entrydate, groupId } = data;
    Object.assign(formCompRef.value.formModel, {
      username,
      name,
      gender,
      job,
      entrydate,
      deptId: groupId,
    });
    // console.log("formCompRef.value", formCompRef.value.formModel);
  });
};

/**
 * 删除人员
 * @param id
 */
const delUser = (id: number) => {
  ElMessageBox.confirm("确认删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delUserApi(id).then((res) => {
        // console.log("res", res);
        if (res.code == -1) {
          ElMessage.error(res.msg);
        } else if (res.code == 0) {
          ElMessage.success("删除成功");
          getUser();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

/**
 * 切换每页条数
 */
const handleSizeChange = (val: number) => {
  // console.log("每页条数", val);
  pageInfo.pageSize = val;
  getUser();
};

/**
 * 切换当前页
 */
const handleCurrentChange = (val: number) => {
  // console.log("当前页", val);
  pageInfo.pageNum = val;
  getUser();
};

/**
 * 获取人员
 */
const getUser = (flag?: string) => {
  Object.assign(searchForm, {
    ...searchForm,
    gender: searchForm.gender == 0 ? "" : searchForm.gender,
  });
  if (flag) {
    exportUserApi({ ...searchForm, export: true }).then((res) =>
      downloadBinaryFile(res, "人员信息.xlsx")
    );
    return;
  }
  getUserApi({ ...searchForm, ...pageInfo }).then((res) => {
    if (res.code == 0) {
      const {
        data: { list, total },
      } = res;
      tableData.value = list;
      totalRef.value = total;
    } else if (res.code == -1) {
      ElMessage.info(res.msg);
      router.replace("/");
    }
  });
};

onMounted(() => {
  getUser();
});
</script>

<style scoped lang="scss"></style>
